<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input clearable @clear="getUserList" v-model="queryData.query" placeholder="请输入内容">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="addUserDialogVisible=true" type="primary">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table
        :data="users"
        stripe
        border
        style="width: 100%">
        <el-table-column
          type="index"
          label="#">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          label="状态">
          <!-- 通过slot-scope来获取到组件内部暴露的数据
          组件内部: <slot :row="item"></slot>
          通过 Scoped slot 可以获取到 row
          用法参考demo table文档 -->
          <template slot-scope="scope">
            <el-switch
              @change="swichChange(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200px">
          <template slot-scope="scope">
            <el-button @click="editUser(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <el-button @click="removeUser(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
          <!-- 分配角色 -->
          <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top-start">
            <el-button @click="setRoles(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      @close="closeAddUserDialog"
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%">
      <el-form ref="addUserForm" :rules="addUserRules" :model="addUserForm" label-width="80px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="addUserDialogVisible = false">取 消</el-button>
      <el-button @click="addUser" type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      @close="resetEdit"
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form ref="editUserForm" :rules="editRules" :model="editUserForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSub">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      @close="resetSelect"
      :visible.sync="roleDialogVisible"
      width="50%">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <div>
          分配新角色：
          <el-select v-model="selectOpt" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subSetRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'user',
  data () {
    const checkEmail = (rule, value, callback) => {
      var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('邮箱格式不合法'))
      }
    }
    const checkMobile = (rule, value, callback) => {
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('手机格式不合法'))
      }
    }
    return {
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      users: [],
      // 控制添加用户对话框显示/隐藏
      addUserDialogVisible: false,
      // 添加用户表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      editForm: [],
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      roleDialogVisible: false,
      userInfo: [],
      rolesList: [],
      selectOpt: ''
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败')
      this.total = res.data.total
      this.users = res.data.users
    },
    // 每页条数发生变化
    handleSizeChange (val) {
      // console.log(val)
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 页码发生变化
    handleCurrentChange (val) {
      // console.log(val)
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 状态发生变化
    async swichChange (user) {
      const { data: res } = await this.$axios.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error(`修改${user.username}状态失败`)
      }
      this.$message.success(`修改${user.username}状态成功`)
    },
    // 对话框关闭
    closeAddUserDialog () {
      this.$refs.addUserForm.resetFields()
    },
    // 点击确定添加用户
    addUser () {
      this.$refs.addUserForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('创建用户失败')
        }
        this.$message.success('创建用户成功')
        this.addUserDialogVisible = false
        this.getUserList()
      })
    },
    // 点击编辑用户
    async editUser (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editForm = res.data
      this.editUserForm.username = this.editForm.username
      this.editUserForm.email = this.editForm.email
      this.editUserForm.mobile = this.editForm.mobile
    },
    // 对话框关闭
    resetEdit () {
      this.$refs.editUserForm.resetFields()
    },
    // 点击确定提交修改
    editUserSub () {
      this.$refs.editUserForm.validate(async flag => {
        if (!flag) return
        this.editDialogVisible = false
        console.log(this.editForm)
        const { data: res } = await this.$axios.put('users/' + this.editForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.getUserList()
      })
    },
    // 点击删除用户
    removeUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('users/' + id)
        if (res.meta.status === 200) {
          this.$message.success('删除成功!')
          this.getUserList()
        } else {
          this.$message.error('删除失败!')
        }
      }).catch(() => {
        // 点击了取消
        this.$message.info('已取消删除')
      })
    },
    // 点击分配用户角色
    async setRoles (row) {
      this.roleDialogVisible = true
      this.userInfo = row
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 点击确定分配用户角色
    async subSetRole () {
      if (!this.selectOpt) this.$message.error('请选择角色')
      // console.log(this.userInfo)
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectOpt
      })
      if (res.meta.status !== 200) return this.$message.error('分配用户角色失败')
      this.$message.success('分配用户角色成功')
      // console.log(res.data)
      this.roleDialogVisible = false
      // console.log(this.users[1].role_name)
      // console.log(this.selectOpt)
      // this.users[1].role_name = this.selectOpt
      this.getUserList()
    },
    resetSelect () {
      this.selectOpt = ''
    }
  }
}
</script>

<style scoped lang='less'>

</style>
